package cn.example.practice.db;

import cn.example.practice.model.User;
import cn.example.practice.util.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User数据访问对象，处理与用户相关的数据库操作
 */
public class UserDao {
    private static final Logger LOGGER = Logger.getLogger(UserDao.class.getName());
    private static final String INSERT_USER = "INSERT INTO shop_user (username, password) VALUES (?, ?)";
    private static final String SELECT_USER_BY_CREDENTIALS = "SELECT id, username, password FROM shop_user WHERE username = ? AND password = ?";
    private static final String SELECT_USER_BY_USERNAME = "SELECT id, username FROM shop_user WHERE username = ?";

    /**
     * 添加新用户
     *
     * @param user 要添加的用户对象
     * @return 添加是否成功
     */
    public boolean addUser(User user) {
        if (user == null || user.getUserName() == null || user.getPassword() == null) {
            LOGGER.warning("Attempted to add invalid user");
            return false;
        }

        try {
            int result = JDBCUtils.executeUpdate(INSERT_USER, user.getUserName(), user.getPassword());
            return result >= 1;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error adding user: " + user.getUserName(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据用户名和密码获取用户
     *
     * @param user 包含用户名和密码的用户对象
     * @return 可选的用户对象
     */
    public Optional<User> getUserByCredentials(User user) {
        if (user == null || user.getUserName() == null || user.getPassword() == null) {
            LOGGER.warning("Invalid credentials provided");
            return Optional.empty();
        }

        try (ResultSet resultSet = JDBCUtils.executeQuery(
                SELECT_USER_BY_CREDENTIALS,
                user.getUserName(),
                user.getPassword())) {

            if (resultSet.next()) {
                return Optional.of(new User(
                        resultSet.getLong("id"),
                        resultSet.getString("username"),
                        resultSet.getString("password")
                ));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error retrieving user by credentials: " + user.getUserName(), e);
        }

        return Optional.empty();
    }

    /**
     * 根据用户名获取用户
     *
     * @param userName 用户名
     * @return 可选的用户对象
     */
    public Optional<User> getUserByName(String userName) {
        if (userName == null || userName.trim().isEmpty()) {
            LOGGER.warning("Invalid username provided");
            return Optional.empty();
        }

        try (ResultSet resultSet = JDBCUtils.executeQuery(SELECT_USER_BY_USERNAME, userName)) {
            if (resultSet.next()) {
                return Optional.of(new User(
                        resultSet.getLong("id"),
                        resultSet.getString("username")
                ));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error retrieving user by username: " + userName, e);
        }

        return Optional.empty();
    }

    /**
     * 检查用户名是否已存在
     *
     * @param userName 要检查的用户名
     * @return 如果用户名已存在返回true，否则返回false
     */
    public boolean isUserNameExists(String userName) {
        return getUserByName(userName).isPresent();
    }
}
